package com.zzyy.study;

import lombok.Getter;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

//资源类，保时米SU7轿跑,本门店有3个销售(3个线程)
class SU7
{
    @Getter
    private int saleTotal;//本门店总体销售额
    public synchronized void saleTotal()
    {
        saleTotal++;
    }

    //ThreadLocal

    /*ThreadLocal<Integer> salePersonal = new ThreadLocal<>(){
        @Override
        protected Integer initialValue()
        {
            return 0;
        }
    };*/

    ThreadLocal<Integer> salePersonal = ThreadLocal.withInitial(() -> 0);
    public void salePersonal()
    {
        salePersonal.set(1+salePersonal.get());
    }

}
/**
 * ThreadLocal案例演示
 * 1 3个销售卖保时米SU7，求3个销售本团队总体销售额
 * 2 3个销售卖保时米SU7，求3个销售的各自独立的个体销售额
 * @auther zzyy
 * @create 2024-04-22 21:33
 */
public class DemoV1 {

    public static void main(String[] args) throws InterruptedException
    {
        //线程    操作  资源类
        SU7 su7 = new SU7();
        CountDownLatch countDownLatch = new CountDownLatch(3);

        for (int i = 1; i <=3; i++) {
            new Thread(() -> {
                try {
                    for (int j = 1; j <= new Random().nextInt(3)+1; j++) {
                        su7.saleTotal();//本门店需要统计的总数
                        su7.salePersonal();//本门店各自销售自己的，独立的销售额
                    }
                    System.out.println(Thread.currentThread().getName()+"\t"+"号销售卖出："+su7.salePersonal.get());
                } finally {
                    countDownLatch.countDown();
                    su7.salePersonal.remove();
                }
            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"\t"+"销售总额："+su7.getSaleTotal());
    }
}
